using Digitalmes.Domain.Entities.Mes.Productions;

namespace Digitalmes.Application.Mes.Productions.WorkOrders.Commands;

/// <summary>
/// 取消工单命令。
/// </summary>
/// <param name="WoId"></param>
public sealed record CancelWorkOrderCommand(long WoId) : IRequest<IResult<bool>>;

internal sealed class CancelWorkOrderCommandHandler(IRepository<ProdWorkOrder> repo) : IRequestHandler<CancelWorkOrderCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(CancelWorkOrderCommand request, CancellationToken cancellationToken)
    {
        var workOrder = await repo.GetByIdAsync(request.WoId, cancellationToken);
        if (workOrder == null)
        {
            return Result.Failure("未找到要更新的工单");
        }

        if (workOrder.Status is not WoStatusEnum.Draft and not WoStatusEnum.Issued)
        {
            return Result.Failure("工单只有在排产前才能取消");
        }

        workOrder.ChangeStatus(WoStatusEnum.Cancelled);
        var ok = await repo.UpdateAsync(workOrder, m => new
        {
            m.LastStatus,
            m.Status,
            m.UpdatedBy,
            m.UpdatedTime,
        }, cancellationToken);
        return Result.From(ok);
    }
}
